<template>
  <div class="staff-management">
    <h2 style="margin-bottom: 20px;">工作人员管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="员工姓名">
          <el-input
            v-model="searchForm.search"
            placeholder="请输入姓名、工号或手机号"
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="职位">
          <el-select
            v-model="searchForm.position"
            placeholder="请选择职位"
            clearable
            style="width: 120px;"
          >
            <el-option label="店长" value="manager" />
            <el-option label="服务员" value="waiter" />
            <el-option label="清洁员" value="cleaner" />
            <el-option label="技术员" value="technician" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 100px;"
          >
            <el-option label="在职" value="active" />
            <el-option label="离职" value="leave" />
            <el-option label="停职" value="suspend" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="getStaff">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="table-actions">
      <div class="actions-left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          添加员工
        </el-button>
        <el-button type="success" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>
    
    <!-- 工作人员表格 -->
    <div class="content-card">
      <el-table
        v-loading="loading"
        :data="staffList"
        style="width: 100%"
      >
        <el-table-column prop="staff_no" label="工号" width="100" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="username" label="用户名" width="120" />
        
        <el-table-column label="职位" width="100">
          <template #default="scope">
            <el-tag :type="getPositionType(scope.row.position)">
              {{ getPositionText(scope.row.position) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="department" label="部门" width="100" />
        
        <el-table-column label="工作状态" width="100">
          <template #default="scope">
            <el-tag :type="getWorkStatusType(scope.row.work_status)">
              {{ getWorkStatusText(scope.row.work_status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" width="80">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="入职时间" width="120">
          <template #default="scope">
            {{ scope.row.hire_date ? formatDate(scope.row.hire_date) : '-' }}
          </template>
        </el-table-column>
        
        <el-table-column label="最后登录" width="160">
          <template #default="scope">
            {{ scope.row.last_login_at ? formatDate(scope.row.last_login_at) : '从未登录' }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewStaff(scope.row)">
              查看
            </el-button>
            <el-button type="text" size="small" @click="editStaff(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="assignTask(scope.row)">
              分配任务
            </el-button>
            <el-button
              type="text"
              size="small"
              style="color: #f56c6c;"
              @click="deleteStaff(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :page-sizes="[10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="getStaff"
          @current-change="getStaff"
        />
      </div>
    </div>
    
    <!-- 员工表单弹窗 -->
    <el-dialog
      v-model="staffDialog.visible"
      :title="staffDialog.isEdit ? '编辑员工' : '添加员工'"
      width="500px"
    >
      <el-form
        ref="staffFormRef"
        :model="staffDialog.form"
        :rules="staffRules"
        label-width="100px"
      >
        <el-form-item label="工号" prop="staff_no">
          <el-input v-model="staffDialog.form.staff_no" :disabled="staffDialog.isEdit" />
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="staffDialog.form.username" :disabled="staffDialog.isEdit" />
        </el-form-item>
        
        <el-form-item v-if="!staffDialog.isEdit" label="密码" prop="password">
          <el-input v-model="staffDialog.form.password" type="password" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="staffDialog.form.name" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="staffDialog.form.phone" />
        </el-form-item>
        
        <el-form-item label="职位" prop="position">
          <el-select v-model="staffDialog.form.position" style="width: 100%;">
            <el-option label="店长" value="manager" />
            <el-option label="服务员" value="waiter" />
            <el-option label="清洁员" value="cleaner" />
            <el-option label="技术员" value="technician" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="部门">
          <el-input v-model="staffDialog.form.department" />
        </el-form-item>
        
        <el-form-item label="入职时间">
          <el-date-picker
            v-model="staffDialog.form.hire_date"
            type="date"
            placeholder="选择入职时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="staffDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveStaff">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/request'

const loading = ref(false)

// 搜索表单
const searchForm = ref({
  search: '',
  position: '',
  status: ''
})

// 工作人员列表
const staffList = ref([])

// 分页
const pagination = ref({
  page: 1,
  per_page: 20,
  total: 0
})

// 员工表单弹窗
const staffDialog = ref({
  visible: false,
  isEdit: false,
  form: {}
})

const staffFormRef = ref()

// 表单验证规则
const staffRules = {
  staff_no: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请选择职位', trigger: 'change' }
  ]
}

// 获取工作人员列表
const getStaff = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      per_page: pagination.value.per_page,
      search: searchForm.value.search,
      position: searchForm.value.position,
      status: searchForm.value.status
    }
    
    const response = await axios.get('/staff', { params })
    
    if (response.success) {
      staffList.value = response.data.staff
      pagination.value = response.data.pagination
    }
  } catch (error) {
    console.error('获取工作人员列表失败:', error)
    ElMessage.error('获取工作人员列表失败')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    search: '',
    position: '',
    status: ''
  }
  getStaff()
}

// 刷新数据
const handleRefresh = () => {
  getStaff()
}

// 添加员工
const handleAdd = () => {
  staffDialog.value = {
    visible: true,
    isEdit: false,
    form: {
      staff_no: '',
      username: '',
      password: '',
      name: '',
      phone: '',
      position: '',
      department: '',
      hire_date: ''
    }
  }
}

// 编辑员工
const editStaff = (staff) => {
  staffDialog.value = {
    visible: true,
    isEdit: true,
    form: { ...staff }
  }
}

// 保存员工
const handleSaveStaff = async () => {
  if (!staffFormRef.value) return
  
  try {
    await staffFormRef.value.validate()
    
    const isEdit = staffDialog.value.isEdit
    const url = isEdit ? `/staff/${staffDialog.value.form.id}` : '/staff'
    const method = isEdit ? 'put' : 'post'
    
    const response = await axios[method](url, staffDialog.value.form)
    
    if (response.success) {
      ElMessage.success(isEdit ? '编辑成功' : '添加成功')
      staffDialog.value.visible = false
      getStaff()
    }
  } catch (error) {
    console.error('保存员工失败:', error)
    ElMessage.error('保存员工失败')
  }
}

// 查看员工
const viewStaff = (staff) => {
  ElMessage.info('查看员工详情功能开发中')
}

// 分配任务
const assignTask = (staff) => {
  ElMessage.info('任务分配功能开发中')
}

// 删除员工
const deleteStaff = async (staff) => {
  try {
    await ElMessageBox.confirm(`确定要删除员工 ${staff.name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/staff/${staff.id}`)
    
    if (response.success) {
      ElMessage.success('删除成功')
      getStaff()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除员工失败:', error)
      ElMessage.error('删除员工失败')
    }
  }
}

// 获取职位文本
const getPositionText = (position) => {
  switch (position) {
    case 'manager': return '店长'
    case 'waiter': return '服务员'
    case 'cleaner': return '清洁员'
    case 'technician': return '技术员'
    default: return position
  }
}

// 获取职位标签类型
const getPositionType = (position) => {
  switch (position) {
    case 'manager': return 'danger'
    case 'waiter': return 'success'
    case 'cleaner': return 'warning'
    case 'technician': return 'primary'
    default: return 'info'
  }
}

// 获取工作状态文本
const getWorkStatusText = (status) => {
  switch (status) {
    case 'on': return '上班'
    case 'off': return '下班'
    case 'busy': return '忙碌'
    default: return status
  }
}

// 获取工作状态标签类型
const getWorkStatusType = (status) => {
  switch (status) {
    case 'on': return 'success'
    case 'off': return 'info'
    case 'busy': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'active': return '在职'
    case 'leave': return '离职'
    case 'suspend': return '停职'
    default: return status
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 'active': return 'success'
    case 'leave': return 'danger'
    case 'suspend': return 'warning'
    default: return 'info'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

onMounted(() => {
  getStaff()
})
</script>

<style lang="scss" scoped>
// 复用已有样式
</style>